#include <QPainter>
#include <QPolygon>
#include <QPointF>
#include <QVector>
#include <math.h>
#include <QDebug>
#include "skline.h"
#include "skpoint.h"

#define PI 3.14159265

SkLine::SkLine(int const& id, SkPoint *p1, SkPoint *p2,QGraphicsItem * parent):
    QGraphicsItem(parent),SkIdAble(id),source(p1),dest(p2)
{
    setZValue(-2);
    setFlag(ItemIsSelectable);
    source->addLine(this);
    dest->addLine(this);
    adjust();
}
SkPoint* SkLine::sourcePoint() const{
    return source;
}
void SkLine::setSourcePoint(SkPoint *p1){
    source = p1;
    adjust();
}
SkPoint * SkLine::destPoint() const{
    return dest;
}
void SkLine::setDestPoint(SkPoint *p2){
    dest = p2;
    adjust();
}

void SkLine::adjust(){
    if (!source || !dest)
        return;

    QLineF line(mapFromItem(source, 0, 0), mapFromItem(dest, 0, 0));

    prepareGeometryChange();

    sourcePn = line.p1() ;
    destPn = line.p2();

}
QPointF SkLine::rotate(qreal angle,const QPointF& p){


    qreal x = cos(angle*PI/180)*p.x() - sin(angle*PI/180)*p.y() ;
    qreal y = sin(angle*PI/180)*p.x() + cos(angle*PI/180)*p.y() ;

    return QPointF(x,y);
}
QPainterPath SkLine::shape() const{
    QPainterPath path;
    QLineF line(sourcePn,destPn);
    QLineF s = line.unitVector();
    QPointF un = QPointF(s.dx(),s.dy());

    QPointF s1 =line.p1()+rotate(90,un);
    QPointF s2 =line.p1()+rotate(-90,un);
    QPointF s3 =line.p2()+rotate(90,un);
    QPointF s4 =line.p2()+rotate(-90,un);

    QPolygonF points;
    points << s1 << s2 << s4 << s3  << s1;
//    qDebug() << points;
    path.addPolygon(points);

    return path;
}
QRectF SkLine::boundingRect() const{
    if (!source || !dest)
        return QRectF();

    return QRectF(sourcePn, QSizeF(destPn.x() - sourcePn.x(),destPn.y() - sourcePn.y()))
        .normalized();

}
void SkLine::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
	Q_UNUSED(option);
	Q_UNUSED(widget);
    if (!source || !dest)
        return;

    QLineF line(sourcePn, destPn);
    if (qFuzzyCompare(line.length(), qreal(0.)))
        return;

    // Draw the line itself
//    painter->setPen(QPen(Qt::green,1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
//    painter->drawPath(shape());
    painter->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
    painter->drawLine(line);
}
